<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <!--<a-modal
      :title="title"
      :width="1200"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">-->

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="栏目">
          <j-dict-select-tag v-decorator="['channelId', {}]" :triggerChange="true" dictCode="cms_channel"/>
        </a-form-item> -->
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="栏目分类">
          <a-checkbox-group
            v-decorator="['channelIdList', {}]"
            name="checkboxgroup"
            :options="plainOptions"
            @change="onChange"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标题">
          <a-input placeholder="请输入标题" v-decorator="['title', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="短标题">
          <a-input placeholder="请输入短标题" v-decorator="['shortTitle', {}]" />
        </a-form-item>
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标题颜色">
          <a-input placeholder="请输入标题颜色" v-decorator="['titleColor', {}]" />
        </a-form-item>-->
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="发布日期">
          <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'releaseDate', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="有效日期">
          <a-date-picker v-decorator="[ 'validDate', {}]" />
        </a-form-item>
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否加粗">
          <a-input placeholder="请输入是否加粗" v-decorator="['isBold', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否置顶">
          <a-input placeholder="请输入是否置顶" v-decorator="['isTop', {}]" />
        </a-form-item>-->
        <!-- <a-form-item
           :labelCol="labelCol"
           :wrapperCol="wrapperCol"
           label="是否推荐">
           <a-input placeholder="请输入是否推荐" v-decorator="['isRecommend', {}]" />
         </a-form-item>-->
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态(0:草稿;1:审核中;2:已审核;3:回收站)">
          <a-input placeholder="请输入状态(0:草稿;1:审核中;2:已审核;3:回收站)" v-decorator="['status', {}]" />
        </a-form-item>-->
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="类型：知识文档、新闻">
          <a-input placeholder="请输入类型：知识文档、新闻" v-decorator="['articleType', {}]" />
        </a-form-item>-->
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否允许评论">
          <a-input-number v-decorator="[ 'commentControl', {}]" />
        </a-form-item>-->
        <!-- <a-form-item
           :labelCol="labelCol"
           :wrapperCol="wrapperCol"
           label="tagStr">
           <a-input placeholder="请输入tagStr" v-decorator="['tagStr', {}]" />
         </a-form-item>
         <a-form-item
           :labelCol="labelCol"
           :wrapperCol="wrapperCol"
           label="原作者">
           <a-input placeholder="请输入原作者" v-decorator="['originAuthor', {}]" />
         </a-form-item>-->
<!--        <a-form-item-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol"-->
<!--          label="来源">-->
<!--          <a-input placeholder="请输入来源" v-decorator="['origin', {}]" />-->
<!--        </a-form-item>-->
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="外链地址">
          <a-input placeholder="外链地址" v-decorator="['originUrl', {}]" />
        </a-form-item>
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="来源链接">
          <a-input placeholder="请输入来源链接" v-decorator="['originUrl', {}]" />
        </a-form-item>-->
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="内容">
          <!--<a-input placeholder="请输入描述" v-decorator="['description', {}]" />-->
          <!--<editor-bar :isClear="isClear" @change="change" v-decorator="['description', {}]"></editor-bar>-->
          <div>
            <TEditor ref="editor" v-model="model.description" />
          </div>
        </a-form-item>
        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否开放：0-开放；1-受限访问（参考cms_article_acl）">
          <a-input-number v-decorator="[ 'isOpen', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="删除标志，0正常，1删除">
          <a-input-number v-decorator="[ 'isDelete', {}]" />
        </a-form-item>-->

        <!--<a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="最后修改日期">
          <a-date-picker v-decorator="[ 'lastUptDate', {}]" />
        </a-form-item>-->

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import moment from 'moment'
import { putAction, httpAction, postAction } from '@/api/manage'
import JUpload from '@/components/jeecg/JUpload'
import ARow from 'ant-design-vue/lib/grid/Row'
import TEditor from '../../../components/TEditor'
import JCategorySelect from '@/components/jeecg/JCategorySelect'
import JImageUpload from '@/components/jeecg/JImageUpload'
import { base64toBlob, blobToBase64, fileToBase64, fileToBlob } from '@/utils/dataTransform'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  name: 'CmsArticleZXModal',
  components: {
    ARow,
    JUpload,
    TEditor,
    JCategorySelect,
    JImageUpload
  },
  data() {
    return {
      plainOptions: ['政策', '通知公告'],
      value: [],
      formType: '',
      previewVisible: false,
      previewImage: '',
      fileList: [],
      isClear: false,
      detail: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        state: { rules: [{ required: true, message: '请输入发布状态，0-未发布；1-已发布!' }] }
      },
      url: {
        add: '/cxm/cmsArticle/add',
        edit: '/cxm/cmsArticle/edit',
        addByChannel: '/cxm/cmsArticle/addByChannel',
        picUrl: '/sys/common/upload'
      }
    }
  },
  props: {
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: 'temp'
    }
  },
  created() {
  },
  methods: {
    onChange(checkedValues) {
      console.log('checked = ', checkedValues)
      console.log('value = ', this.value)
    },
    // 图片上传
    handlePreviewCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      console.log(this.fileList)
      return false
    },

    change(val) {
      this.model.description = val
    },
    editbychannelid(cmsChannel) {
      let httpurl = this.url.addByChannel
      let parameter = {
        cmsChannel: cmsChannel
      }
      putAction(httpurl, parameter).then((res) => {
        this.list = res.result
        this.form.resetFields()
        this.model = Object.assign({}, res.result)

        this.visible = true
        this.$nextTick(() => {
          //this.form.setFieldsValue(pick(this.model,'channelId','userId','departId','siteId','title','shortTitle','titleColor','isBold','isTop','isRecommend','status','articleType','commentControl','tagStr','originAuthor','origin','originUrl','description','isOpen','isDelete','attachment','state'))

          this.form.setFieldsValue(pick(this.model, 'title', 'shortTitle', 'description', 'attachment', 'coverPicture', 'channelIdList'))
          this.form.setFieldsValue({
            description: this.model.description ? this.model.description : ''
          })
          //时间格式化
          this.form.setFieldsValue({ releaseDate: this.model.releaseDate ? moment(this.model.releaseDate) : null })
          this.form.setFieldsValue({ validDate: this.model.validDate ? moment(this.model.validDate) : null })
          //this.form.setFieldsValue({lastUptDate:this.model.lastUptDate?moment(this.model.lastUptDate):null})
        })
      }).finally(() => {

      })
    },
    add(record) {
      if (record == '公告') {
        this.formType = '公告'
        this.edit({})
      } else {
        this.formType = '政策'
        this.edit({})
      }
    },
    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      //图片回显
      console.log(record.coverPicture)
      let coverPicture = process.env.VUE_APP_BASE_API + record.coverPicture
      console.log(coverPicture)
      if (record.coverPicture) {
        // this.
        this.fileList[0] = {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: process.env.VUE_APP_BASE_API + record.coverPicture
        }
      }

      this.visible = true
      this.$nextTick(() => {
        //this.form.setFieldsValue(pick(this.model,'channelId','userId','departId','siteId','title','shortTitle','titleColor','isBold','isTop','isRecommend','status','articleType','commentControl','tagStr','originAuthor','origin','originUrl','description','isOpen','isDelete','attachment','state'))
        this.form.setFieldsValue(pick(this.model, 'title', 'shortTitle', 'attachment', 'channelId', 'origin', 'originUrl', 'coverPicture', 'channelIdList'))
        this.form.setFieldsValue({
          description: this.model.description ? this.model.description : ''
        })
        //时间格式化
        this.form.setFieldsValue({ releaseDate: this.model.releaseDate ? moment(this.model.releaseDate) : null })
        this.form.setFieldsValue({ validDate: this.model.validDate ? moment(this.model.validDate) : null })
        //this.form.setFieldsValue({lastUptDate:this.model.lastUptDate?moment(this.model.lastUptDate):null})
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.fileList = []
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (err) {
          console.log(err)
        }
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化
          if (formData.channelIdList) {
            if (formData.channelIdList.length == 2) {
              //将数组转化成以逗号分隔的字符串
              formData.channelId = formData.channelIdList.join(',')
            } else {
              formData.channelId = formData.channelIdList[0]
            }
          }
          formData.releaseDate = formData.releaseDate ? formData.releaseDate.format('YYYY-MM-DD HH:mm:ss') : null
          formData.validDate = formData.validDate ? formData.validDate.format() : null
          formData.description = this.model.description ? this.model.description : ''
          //formData.lastUptDate = formData.lastUptDate?formData.lastUptDate.format():null;
          console.log(formData)
          if (this.fileList.length > 0) {
            // 有图片时
            console.log(this.fileList[0])
            let file = this.fileList[0].originFileObj
            let filetype = this.fileList[0].name.split('.')[1]
            let filename = this.fileList[0].name
            let blob = fileToBlob(file)
            //创建表单数据
            let formData2 = new FormData()
            //追加文件数据
            formData2.append('file', blob, filename)
            formData2.append('biz', this.bizPath)
            postAction(that.url.picUrl, formData2).then((res) => {
              if (res.success) {
                console.log(res)
                let coverPicture = res.message
                formData.coverPicture = coverPicture
                httpAction(httpurl, formData, method).then((res) => {
                  if (res.success) {
                    that.$message.success(res.message)
                    that.$emit('ok')
                  } else {
                    that.$message.warning(res.message)
                  }
                }).finally(() => {
                  that.confirmLoading = false
                  that.close()
                })
              } else {
                that.$message.warning(res.message)
              }
            })
          } else {
            //没图片提交表单
            console.log(formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
              that.$parent.$parent.loadData()
            })
          }

        }
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style lang="less" scoped>
///deep/ .ant-modal-wrap .ant-modal{
//  width: 300px;
//  //margin-top: 200px  //height: 128px;
//}
///deep/ .ant-modal-root .ant-modal-wrap .ant-modal .ant-modal-content{
//  margin-top: 300px;
//}
</style>